<template>
  <div class="form-group">
    <h5 class="table-title space-m-b" v-if="title && title!==''">{{ title }}</h5>
    <a-row class="form-row" type="flex" :gutter="16">
      <a-col
        :lg="item.colspan || 6"
        :md="12"
        :sm="24"
        v-for="(item,index) in data"
        :key="index"
        v-show="!item.hidden">

        <a-form-item :label="item.label" v-if="item.type === 'fileUpload'" class="item-upload">
          <div class="d-uploadList" v-if="item.uploadList && item.uploadList.length > 0">
            <em v-for="(f,i) in item.uploadList" :key="i" @click="openUrl(f)">{{f.substring(f.lastIndexOf('.'))}}<i @click.stop="uploadListDeleteItem(item , i)" v-if="item.isDelete">x</i></em>
          </div>
          <!--不显示上传按钮的时候，上传文件数量为0时-->
          <div v-if="!item.isUpload && (!item.uploadList || item.uploadList.length < 1)">
            无
          </div>

          <a-upload 
          v-if="item.isUpload" 
          :accept="item.accept" 
          name="file" 
          action="/api/dfs/dfs/upload" 
          :headers="item.headers" 
          :showUploadList="false" 
          @change="item.handleChange" 
          :beforeUpload="item.beforeUpload"
          v-decorator="[item.key , {initialValue: formData[item.key]}]"
          >
            <a-button type="primary" icon="upload">上传</a-button>
          </a-upload>
          <em style="display:inline-block; font-style:normal; margin-left:20px;">{{item.tip}}</em>
        </a-form-item>

        <a-form-item :label="item.label" v-if="item.type === 'inputSearch'">
          <a-input-search
            :placeholder="!item.disabled ? (item.placeholder ? item.placeholder : '请输入'+item.label) : ''"
            style="width:100%"
            :disabled="item.disabled"
            @search="item.onSearch"
            v-decorator="[
              item.key,
              {initialValue:formData[item.key], rules: [Object.assign({message:`请输入${item.label}`},item.rules), {validator: item.validator}]}
            ]" />
        </a-form-item>
        <a-form-item :label="item.label" v-if="item.type === 'input'">
          <a-input
            :placeholder="!item.disabled ? (item.placeholder ? item.placeholder : '请输入'+item.label) : ''"
            :disabled="item.disabled"
            :type="item.inputType || 'text'"
            v-decorator="[
              item.key,
              {initialValue:formData[item.key], rules: [Object.assign({message:`请输入${item.label}`},item.rules), {validator: item.validator}]}
            ]" />
        </a-form-item>
        <a-form-item :label="item.label" v-if="item.type === 'radio'">
          <a-radio-group
            :disabled="item.disabled"
            v-decorator="[item.key, {initialValue:formData[item.key], rules: [Object.assign({message:`请选择${item.label}`},item.rules), {validator: item.validator}]}]"
          >
            <a-radio
              :value="subitem.value"
              v-for="(subitem, key) in item.radioList"
              :key="key"
            >
              {{ subitem.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label="item.label" v-if="item.type === 'select'">
          <a-select
            :placeholder="!item.disabled ? (item.placeholder ? item.placeholder : '请选择'+item.label) : ''"
            :disabled="item.disabled"
            :default-active-first-option="false"
            :show-search="item.showSearch"
            :show-arrow="true"
            :filter-option="function(input, option){return option.componentOptions.children[0].text.indexOf(input) >= 0}"
            @search="(val) => {const fun = item.onSearch ? item.onSearch : ()=>{}; fun(val)}"
            @change="item.onChange"
            v-decorator="[
              item.key,
              {...selectDecorator(item), rules: [Object.assign({message:`请选择${item.label}`},item.rules), {validator: item.validator}]}
            ]">
            <a-select-option
              :value="subitem.value"
              v-for="(subitem, key) in item.selectList"
              :key="key">{{ subitem.label.replace(/\s/g,'') }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="item.label" v-if="item.type === 'inputAuto'">
          <a-auto-complete
            style="width:100%"
            @search="item.onSearch"
            :placeholder="!item.disabled ? (item.placeholder ? item.placeholder : '请输入'+item.label) : ''"
            :disabled="item.disabled"
            v-decorator="[
              item.key,
              {initialValue:formData[item.key], rules: [Object.assign({message:`请输入${item.label}`},item.rules), {validator: item.validator}]}
            ]"
          > <template slot="dataSource">
            <a-select-option v-for="subitem in item.selectList" :key="subitem.label">{{ subitem.label.replace(/\s/g,'') }}</a-select-option>
          </template>
          </a-auto-complete>
        </a-form-item>
        <a-form-item :label="item.label" v-if="item.type === 'dateTime'">
          <a-date-picker
            :format="item.format"
            :placeholder="!item.disabled ? (item.placeholder ? item.placeholder : '请选择'+item.label) : ''"
            :disabled="item.disabled"
            :show-time="item.showTime"
            @change="dateTimeChange"
            style="width:100%; min-width:auto;"
            v-decorator="[item.key, {initialValue:formData[item.key] ? moment(new Date(formData[item.key]), item.format) : undefined, rules: [Object.assign({message:`请选择${item.label}`},item.rules)]}]"
          />
        </a-form-item>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import moment from 'moment'
import { downloadFile } from '@/api/referral'
export default {
  name: 'CreateForm',
  props: {
    formSource: {
      type: [Array, Object],
      default: null
    },
    formData: {
      type: Object,
      default: null
    },
    title: {
      type: String,
      default: ''
    },
    status: {
      type: String,
      default: 'add'
    }
  },
  data () {
    return {
      data: this.formSource
    }
  },
  created () {
    var that = this
    // 给动态表单添加自定义校验
    for (const key in this.data) {
      const item = this.data[key]
      item.validator && (item.validator = that[item.validator])
    }

    
  },
  methods: {
    uploadListDeleteItem(item ,i){
      //记录删除过的上传了的
      var name = 'uploadList_' + item.key + '_deleteItems';
      var arr = localStorage.getItem(name) ? JSON.parse(localStorage.getItem(name)) : [];
      arr.push(item.uploadList[i]);
      localStorage.setItem(name , JSON.stringify(arr))

      item.uploadList.splice(i,1)
      console.log(name , localStorage.getItem(name))
    },
    openUrl(filePath){
      downloadFile(filePath).then(response => {
        // const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        var blob = new Blob([response], {type: 'application/octet-stream'});
        let url = window.URL.createObjectURL(blob)
        var el = document.createElement("a");
        document.body.appendChild(el);
        el.href = url;
        el.download = filePath.substring(filePath.lastIndexOf('/'))
        el.click();
        window.URL.revokeObjectURL(url);
      });
    },
    moment,
    selectDecorator (item) {
      if (this.formData[item.key]) {
        return { initialValue: this.formData[item.key] }
      } else {
        return { initialValue: undefined }
      }
    },
    dateTimeChange (val) {
      if (!val) {
        console.log(val)
      }
    },
    validateAge (rule, value, callback) {
      if (isNaN(value) || value >= 150) {
        callback(new Error('请输入正确的年龄'))
      }
      callback()
    }
    // validate (rule, value, callback) {
    //   const regex = /^user-(.*)$/
    //   if (!regex.test(value)) {
    //     callback(new Error('需要以 user- 开头'))
    //   }
    //   callback()
    // }
  }
}
</script>

<style scoped>
/deep/.item-upload .ant-form-item-children{ align-items: flex-start; display: flex;}
.d-uploadList{ display: flex; max-width:50%; overflow: hidden; margin-right:20px; padding-top:5px;}
.d-uploadList em{ display: block; border:solid #40a9ff 1px; height:30px; line-height: 30px; padding:0 10px; margin-right:15px; position: relative; font-style: normal; color:#40a9ff; cursor: pointer;}
.d-uploadList em i{ position: absolute; right:-10px; top:-5px; display: block; width:20px; height:20px; line-height: 18px; text-align: center; border-radius: 100%; overflow: hidden; background: #40a9ff; color:#fff; font-style: normal; cursor: pointer;}
.d-uploadList em i:hover{ background: #f00;}
</style>
